//
//  LoginController.m
//  SleepingElf
//
//  Created by karong on 2023/10/24.
//

#import "LoginController.h"
#import <Firebase.h>
#import <FirebaseAuth/FirebaseAuth.h>
#import <AuthenticationServices/AuthenticationServices.h>
#import "BaseTabBarController.h"
#import <GoogleSignIn/GoogleSignIn.h>
#import <FBSDKCoreKit/FBSDKCoreKit.h>
#import <FBSDKLoginKit/FBSDKLoginKit.h>

@interface LoginController () <ASAuthorizationControllerDelegate, ASAuthorizationControllerPresentationContextProviding>
@property (weak, nonatomic) IBOutlet UIView *appleView;
@property (weak, nonatomic) IBOutlet UIView *appIdView;
@property (weak, nonatomic) IBOutlet UIView *googleView;
@property (weak, nonatomic) IBOutlet UIView *facebookView;
@property (weak, nonatomic) IBOutlet UIButton *checkBoxBtn;
@property (weak, nonatomic) IBOutlet UIView *mainView;
@property (weak, nonatomic) IBOutlet UIButton *languageBtn;
@property (strong, nonatomic) NSString *appleNonce;
@end

@implementation LoginController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self layoutView];
    [self layoutLanguage];
}

- (void)layoutLanguage {
    NSString * language = languageStrArray[appConfig.languageType];
    [self.languageBtn setTitle:language forState:(UIControlStateNormal)];
}

- (void)layoutView {
    NSInteger btnCount = 0;
    if (@available(iOS 13.0, *)) {
        btnCount ++;
        [self createAppleLoginView];
    }
    else {
        [self.appleView removeFromSuperview];
    }
    [self layoutBottomLabel];
}

- (void)layoutBottomLabel {
    YYLabel *label = [[YYLabel alloc] init];
    label.numberOfLines = 0;
    label.textAlignment = NSTextAlignmentCenter;
    [self.mainView addSubview:label];
    [label mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.checkBoxBtn.mas_right).offset(4);
        make.top.bottom.right.mas_equalTo(self.mainView);
    }];
    
    NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
    style.alignment = NSTextAlignmentCenter;
    style.lineBreakMode = NSLineBreakByWordWrapping;
    NSString *text = WSLocalized(@"已阅读并同意《用户协议》和《隐私政策》");
    NSMutableAttributedString *attrText = [[NSMutableAttributedString alloc] initWithString:text
                                                                                 attributes:@{NSFontAttributeName: [UIFont systemFontOfSize:14], NSParagraphStyleAttributeName: style, NSForegroundColorAttributeName: [UIColor colorFromHexRGB:@"9DA5CA"]}];
    
    NSString *string1 = WSLocalized(@"《用户协议》");
    NSRange range1 = [text rangeOfString:string1];
    [attrText addAttributes:@{NSUnderlineStyleAttributeName: @(1)} range:range1];
    [attrText setTextHighlightRange:range1 color:[UIColor colorFromHexRGB:@"9DA5CA"] backgroundColor:nil tapAction:^(UIView * _Nonnull containerView, NSAttributedString * _Nonnull text, NSRange range, CGRect rect) {
                UIViewController * target = [[CTMediator sharedInstance]ct_showWebWithUrl:API_AGREEMENT_USER titleStr:WSLocalized(@"用户协议") showNav:YES closeHandle:^{}];
                [self.navigationController pushViewController:target animated:YES];
    }];
    
    NSString *string2 = WSLocalized(@"《隐私政策》");
    NSRange range2 = [text rangeOfString:string2];
    [attrText addAttributes:@{NSUnderlineStyleAttributeName: @(1)} range:range2];
    [attrText setTextHighlightRange:range2 color:[UIColor colorFromHexRGB:@"9DA5CA"] backgroundColor:nil tapAction:^(UIView * _Nonnull containerView, NSAttributedString * _Nonnull text, NSRange range, CGRect rect) {
                UIViewController * target = [[CTMediator sharedInstance]ct_showWebWithUrl:API_AGREEMENT_PRIVACY titleStr:WSLocalized(@"隐私政策") showNav:YES closeHandle:^{}];
                [self.navigationController pushViewController:target animated:YES];
    }];
    label.attributedText = attrText;
}

- (void)createAppleLoginView {
    if (@available(iOS 13.0, *)) {
        ASAuthorizationAppleIDButton *appleIDButton = [[ASAuthorizationAppleIDButton alloc] initWithAuthorizationButtonType:ASAuthorizationAppleIDButtonTypeSignIn authorizationButtonStyle:ASAuthorizationAppleIDButtonStyleWhite];
        appleIDButton.frame = CGRectMake(0, 0, kScreenWidth - 66, 44);
        appleIDButton.layer.masksToBounds = YES;
        appleIDButton.layer.cornerRadius = 22;
        appleIDButton.tag = 10000;
        [appleIDButton addTarget:self action:@selector(appleLoginAction:) forControlEvents:UIControlEventTouchUpInside];
        [self.appIdView addSubview:appleIDButton];

    }
}

- (void)loginRequest {
    WeakSelf
    [UserRequest loginWithSuccess:^(id obj) {
        [SEToast dismiss];
        [weakSelf showMainViewController];
    } failed:^(NSURLResponse * _Nonnull response, NSError * _Nonnull error, id  _Nonnull responseObject) {

    }];
}

- (void)showMainViewController {
    BaseNavigationController * nav = [[BaseNavigationController alloc]initWithRootViewController:[BaseTabBarController new]];
    nav.navigationBarHidden = YES;
    typedef void (^Animation)(void);
    UIWindow* window = [UIApplication sharedApplication].keyWindow;
    window.rootViewController.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
    Animation animation = ^{
        BOOL oldState = [UIView areAnimationsEnabled];
        [UIView setAnimationsEnabled:NO];
        [UIApplication sharedApplication].keyWindow.rootViewController = nav;
        [UIView setAnimationsEnabled:oldState];
    };
    [UIView transitionWithView:window
                      duration:0.5f
                       options:UIViewAnimationOptionTransitionCrossDissolve
                    animations:animation
                    completion:^(BOOL finished) {}];
}

//游客登錄
- (void)visitorRegist:(NSString *)userName password:(NSString *)password{
    [[FIRAuth auth]signOut:nil];
    [appUserCenter logOut];
    WeakSelf
    [[FIRAuth auth] signInWithEmail:userName
                           password:password
                         completion:^(FIRAuthDataResult * _Nullable authResult,
                                      NSError * _Nullable error) {
        if (error) {
            [SEToast simple:error.domain];
        }else{
            FIRUser *user = authResult.user;
            [user getIDTokenWithCompletion:^(NSString * _Nullable token, NSError * _Nullable error) {
                appUserCenter.qtoken = token;
                [weakSelf loginRequest];
            }];
        }
    }];
}

- (IBAction)fastLoginLoginAction:(id)sender {
    if (!self.checkBoxBtn.selected) {
        [SEToast simple:WSLocalized(@"请先阅读并同意《用户协议》和《隐私政策》")];
        return;
    }
    [SEToast loadingFull];
    [[FIRAuth auth]signOut:nil];
    [appUserCenter logOut];
    NSString *userNameStr = [NSString stringWithFormat:@"%@@SleepingElf.com",[SEUserCenter uuid]];
    NSString *password = @"SleepingElf123456";
    [[FIRAuth auth] createUserWithEmail:userNameStr
                               password:password
                             completion:^(FIRAuthDataResult * _Nullable authResult,
                                          NSError * _Nullable error) {
        if (error) {
            [self visitorRegist:userNameStr password:password];
        }else{
            FIRUser *user = authResult.user;
            [user getIDTokenWithCompletion:^(NSString * _Nullable token, NSError * _Nullable error) {
                appUserCenter.qtoken = token;
                [self loginRequest];
            }];
        }
    }];
}

- (IBAction)appleLoginAction:(id)sender {
    if (!self.checkBoxBtn.selected) {
        [SEToast simple:WSLocalized(@"请先阅读并同意《用户协议》和《隐私政策》")];
        return;
    }
    [SEToast loadingFull];
    if (@available(iOS 13.0, *)) {
        self.appleNonce = [Tools randomNonce:32];
        ASAuthorizationAppleIDProvider *appleIDProvider = [[ASAuthorizationAppleIDProvider alloc]init];
        ASAuthorizationAppleIDRequest *request = [appleIDProvider createRequest];
        request.requestedScopes = @[ASAuthorizationScopeFullName,ASAuthorizationScopeEmail];
        request.nonce = [Tools stringBySha256HashingString:self.appleNonce];
        ASAuthorizationController *auth = [[ASAuthorizationController alloc]initWithAuthorizationRequests:@[request]];
        auth.delegate = self;
        auth.presentationContextProvider = self;
        [auth performRequests];
    }
}

- (IBAction)googleLoginAction:(UIButton *)sender {
    if (!self.checkBoxBtn.selected) {
        [SEToast simple:WSLocalized(@"请先阅读并同意《用户协议》和《隐私政策》")];
        return;
    }
    [SEToast loadingFull];
    [[GIDSignIn sharedInstance] signOut];
    GIDConfiguration *config = [[GIDConfiguration alloc] initWithClientID:[FIRApp defaultApp].options.clientID];
    [GIDSignIn.sharedInstance setConfiguration:config];
    [GIDSignIn.sharedInstance signInWithPresentingViewController:self completion:^(GIDSignInResult * _Nullable signInResult, NSError * _Nullable error) {
        //error.code != -5 用戶退出
        if(error) {
            [SEToast dismiss];
            if(!signInResult.user && !signInResult.user.profile && error.code != -5) {
                [SEToast simple:SESF(@"Login failed\n%@", error.localizedDescription)];
            };
        }
        else {
            [signInResult.user refreshTokensIfNeededWithCompletion:^(GIDGoogleUser * _Nullable user,
                                                                                   NSError * _Nullable error) {
                              if (error) {
                                  NSLog(@"%@", error.localizedDescription);
                              } else {
                                  if (user == nil) {
                                      NSLog(@"signInResult.user is nil");
                                  } else {
                                      NSLog(@"user.userID:%@", user.userID);
                                      NSLog(@"user.idToken.tokenString:%@", user.idToken.tokenString);
                                  }
                              }
                          }];
            FIRAuthCredential *credential = [FIRGoogleAuthProvider credentialWithIDToken:signInResult.user.idToken.tokenString accessToken:signInResult.user.accessToken.tokenString];
            [self signInFirebaseWithCredential:credential accountType:0];
        }
    }];
}

- (IBAction)facebookLoginAction:(UIButton *)sender {
    if (!self.checkBoxBtn.selected) {
        [SEToast simple:WSLocalized(@"请先阅读并同意《用户协议》和《隐私政策》")];
        return;
    }
    FBSDKLoginManager *login = [[FBSDKLoginManager alloc] init];
    [login logOut];
    [login logInWithPermissions:@[@"public_profile", @"email"] fromViewController:self handler:^(FBSDKLoginManagerLoginResult * _Nullable result, NSError * _Nullable error) {
        if (error) {
            [SEToast simple:SESF(@"Login failed\n%@", error.localizedDescription)];
        }
        else if(result.token) {
            [SEToast loading];
            FIRAuthCredential *credential = [FIRFacebookAuthProvider credentialWithAccessToken:[FBSDKAccessToken currentAccessToken].tokenString];
            [self signInFirebaseWithCredential:credential accountType:0];
        }
    }];
}

- (IBAction)skipAction:(id)sender {
    [self showMainViewController];
}

- (IBAction)languageAction:(id)sender {
    UIStoryboard *storyBoard = [UIStoryboard storyboardWithName:@"MeController" bundle:nil];
    UIViewController * target = [storyBoard instantiateViewControllerWithIdentifier:@"LanguagePicker"];
    target.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
    target.modalPresentationStyle = UIModalPresentationCustom;
    [self presentViewController:target animated:YES completion:nil];
}

///代理主要用於展示在哪里
-(ASPresentationAnchor)presentationAnchorForAuthorizationController:(ASAuthorizationController *)controller API_AVAILABLE(ios(13.0)){
    return self.view.window;
}

-(void)authorizationController:(ASAuthorizationController *)controller didCompleteWithAuthorization:(ASAuthorization *)authorization API_AVAILABLE(ios(13.0)){
    if([authorization.credential isKindOfClass:[ASAuthorizationAppleIDCredential class]]){
        ASAuthorizationAppleIDCredential *appleIDCredential = (ASAuthorizationAppleIDCredential *)authorization.credential;
        if (appleIDCredential.identityToken == nil) {
            [SEToast simple:@"Unable to fetch identity token."];
            return;
        }
        NSString *idToken = [[NSString alloc] initWithData:appleIDCredential.identityToken encoding:NSUTF8StringEncoding];
        if (idToken == nil) {
            [SEToast simple:@"Unable to serialize id token from data"];
            return;
        }
        
        // Initialize a Firebase credential.
        FIROAuthCredential *credential = [FIROAuthProvider credentialWithProviderID:@"apple.com" IDToken:idToken rawNonce:self.appleNonce];
        [self signInFirebaseWithCredential:credential accountType:0];
    }
}

///回调失敗
-(void)authorizationController:(ASAuthorizationController *)controller didCompleteWithError:(NSError *)error API_AVAILABLE(ios(13.0)){
    NSString *errorMsg = nil;
    switch (error.code) {
        case ASAuthorizationErrorCanceled:
            errorMsg = WSLocalized(@"用戶取消了授權請求");
            break;
        case ASAuthorizationErrorFailed:
            errorMsg = WSLocalized(@"授權請求失敗");
            break;
        case ASAuthorizationErrorInvalidResponse:
            errorMsg = WSLocalized(@"授權請求響應無效");
            break;
        case ASAuthorizationErrorNotHandled:
            errorMsg = WSLocalized(@"未能處理授權請求");
            break;
        case ASAuthorizationErrorUnknown:
            errorMsg = WSLocalized(@"授權請求失敗未知原因");
            break;
    }
    [SEToast simple:errorMsg];
}

- (void)signInFirebaseWithCredential:(FIRAuthCredential *)credential accountType:(NSInteger)accountType {
    [[FIRAuth auth] signInWithCredential:credential completion:^(FIRAuthDataResult * _Nullable authResult, NSError * _Nullable error) {
        if (error || !authResult.user) {
            [SEToast simple:error.domain];
        }
        else {
            NSString *avator;
            if (authResult.user.photoURL) {
                avator = authResult.user.photoURL.absoluteString;
            }
            FIRUser *user = authResult.user;
            [user getIDTokenWithCompletion:^(NSString * _Nullable token, NSError * _Nullable error) {
                appUserCenter.qtoken = token;
                [self loginRequest];
            }];
            
        }
    }];
}

- (IBAction)checkBoxAction:(UIButton *)sender {
    sender.selected = !sender.selected;
}
@end
